// pages/push/push.js
const request = require("../../utils/request.js");
const app = getApp();

Page({
  /**
   * 页面的初始数据
   */
  data: {
    live:[],
    frontCamera: true,
    cameraContext: {},
    pushUrl: "",
    mode: "SD",
    muted: false,
    enableCamera: true,
    orientation: "vertical",
    beauty: 6.3,
    whiteness: 3.0,
    backgroundMute: false,
    debug: false,
    headerHeight: app.globalData.headerHeight,
    statusBarHeight: app.globalData.statusBarHeight,
    pushMessage:[],
    hideFlag: true,//true-隐藏  false-显示
    animationData: {},//
    nowProduct:false,
    productList:[],
    flag:true,
    modelBot:false,
    loginNum:1,
    client_list:[],
    dianzan:0,
    avatarUrl: "",//用户头像
    hidel:true
     
    

  },
  goback(){
    let that = this
    wx.showModal({
      title: '提示',
      content: '确认要下播吗？',
      success: function (res) {
        if (res.confirm) {
          wx.navigateBack({
            delta: 1,
            success(){
              // console.log(that.data.cameraContext)
              // that.data.cameraContext.stop()
             
            }
          });
        } else {
          console.log('点击取消回调')
        }
      }
    })

  
    
  },
  showModelBot:function(){
    this.setData({
      modelBot:!this.data.modelBot
    })
  },
  getOption: function (e) {
    var that = this;
    that.setData({
      value: e.currentTarget.dataset.value,
      hideFlag: true,
      hidel:true
    })
  },
  //取消
  mCancel: function () {
    var that = this;
    that.hideModal();
  },

  
  // 显示遮罩层
  showModal: function () {
    var that = this;
    that.setData({
      hideFlag: false,
      hidel:false
    })

    var animation = wx.createAnimation({
      duration: 400,
      timingFunction: 'ease',
    })
    this.animation = animation; 
    var time1 = setTimeout(function () {
      that.slideIn();
      clearTimeout(time1);
      time1 = null;
    }, 100)
  },

  // 隐藏遮罩层
  hideModal: function () {
    var that = this;
    var animation = wx.createAnimation({
      duration: 400,
      timingFunction: 'ease',
    })
    this.animation = animation
    that.slideDown();
    var time1 = setTimeout(function () {
      that.setData({
        hideFlag: true,
        hidel:true
      })
      clearTimeout(time1);
      time1 = null;
    }, 220)

  },
  
  slideIn: function () {
    this.animation.translateY(0).step()
    this.setData({
     
      animationData: this.animation.export()
    })
  },
  lower:function(){
    var list = this.data.productList;
    var that = this;
    var pagenum = list.length/4+1;
    
    if(pagenum<2){
      return false
    } else if (this.data.flag){
      wx.request({
        url: `${app.globalData.natappvipindex}?i=${that.data.live['uniacid']}&c=entry&m=lexiangpingou&do=goods&ac=list&op=shopajax&is_hunda=1&page=${pagenum}&pagesize=4&noliveinfo=1&nocategory=1`,
        data: '',
        header: {},
        method: 'GET',
        dataType: 'json',
        responseType: 'text',
        success: function (res) {
          // let list = JSON.parse()
          if(res.data.list.length<4){
            that.setData({
              flag:false
            },()=>{
              wx.showToast({
                title: '没有数据了',
                duration: 300
              });
              return false;
            })
          }
          console.log(res.data.list)
          let cont = list.concat(res.data.list)
          if(res.data.list.length==0){
            wx.showToast({ 
              title: '没有数据了',
              duration: 300
            });
            return false;
          }else{
            wx.showToast({
              title: '正在加载中',
              icon:'loading',
              duration: 300
            });
            setTimeout(()=>{
              that.setData({
                productList:cont
              })
            },500)
          }
        },
        fail: function (res) { },
        complete: function (res) { },
      })
    }
  },
  slideDown: function () {
    this.animation.translateY(300).step()
    this.setData({
      animationData: this.animation.export(),
    })
  },

  onSwitchCameraClick: function() {
    console.log('fanzhuan')
    this.data.frontCamera = !this.data.frontCamera;
    this.setData({
      frontCamera: this.data.frontCamera,
      modelBot:!this.data.modelBot
    });
    this.data.cameraContext.switchCamera();
  },
  onBeautyClick: function() {
    if (this.data.beauty != 0) {
      this.data.beauty = 0;
      this.data.whiteness = 0;
    } else {
      this.data.beauty = 6.3;
      this.data.whiteness = 3.0;
    }

    this.setData({
      beauty: this.data.beauty,
      whiteness: this.data.whiteness
    });
  },
  onLogClick: function() {
    this.setData({
      debug: !this.data.debug
    });
  },
  onMuteClick: function() {
    this.setData({
      muted: !this.data.muted,
      modelBot:!this.data.modelBot
    });
  },
  onPushEvent: function(e) {
    console.log(e.detail.code);

    if (e.detail.code == -1307) {
      this.stop();
      wx.showToast({
        title: "推流多次失败"
      });
    }
  },
  setProduct(){
    console.log(1)
  },
  stop: function() {
    this.setData({
      playing: false,
      pushUrl: "",
      mode: "SD",
      muted: false,
      enableCamera: true,
      orientation: "vertical",
      beauty: 6.3,
      whiteness: 3.0,
      backgroundMute: false,
      debug: false
    });
    this.data.cameraContext.stop();
  },

  createContext: function() {
    var self = this;
    this.setData(
      {
        cameraContext: wx.createLivePusherContext("camera-push")
      },
      () => {
        self.data.cameraContext.start();
      }
    );
  },
  successFun(res) {
    console.log(res)
  },
  failFun(res){
    console.log(res)
  },
  length(obj) {
    var count = 0;
    for (var i in obj) {
      count++;
    }
    return count;
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;
    // this.onLoad()
    console.log('onload')
    var live = wx.getStorageSync("live");
    var live = live['live'];
    this.setData({
      live: live
    })
    wx.request({
      url: `${app.globalData.dev}?op=OverLiveInfo&uniacid=${live.uniacid}`,
      data: '',
      header: {},
      method: 'get',
      dataType: 'json',
      responseType: 'text',
      success(res) {
        console.log(res)
        if(res.data.zan==null){
          res.data.zan=0
        }
        that.setData({
          dianzan: res.data.zan
        })
      }
    })
    setInterval(() => {
      wx.request({
        url: `${app.globalData.dev}?op=OverLiveInfo&uniacid=${live.uniacid}`,
        data:'',
        header:{},
        method:'get',
        dataType:'json',
        responseType: 'text',
        success(res){
          console.log(res)
          if(res.data.zan==null){
            res.data.zan=0
          }
          that.setData({
            dianzan:res.data.zan
          })
        }
      })
    }, 10000)
    //加载list
    
    wx.getUserInfo({
      success(res){
        console.log(res)
        that.setData({
          avatarUrl: res.userInfo.avatarUrl
        })
      }
    })
    wx.request({
      url: `${app.globalData.natappvipindex}?i=${live.uniacid}&c=entry&m=lexiangpingou&do=goods&ac=list&op=shopajax&is_hunda=1&page=1&pagesize=4&noliveinfo=1&nocategory=1`,
      data: '',
      header: {},
      method: 'GET',
      dataType: 'json',
      responseType: 'text',
      success: function(res) {
        // let list = JSON.parse()
        that.setData({
          productList: res.data.list
        })
        console.log(res)
      },
      fail: function(res) {},
      complete: function(res) {},
    })
    
    console.log("onLoad");
    let socketOpen = false;
    // let that = this
    wx.connectSocket({
      url: app.globalData.wsspath
    });
    var name = "主播";
    var roomid = live.uniacid;
    if (socketOpen == false) {
    wx.onSocketOpen(function(res) {
        socketOpen = true;
        console.log("WebSocket连接已打开！");
        var login_data =
          '{"type":"login","client_name":"' +
          name.replace(/"/g, '\\"') +
          '","room_id":' +
          roomid +
          "}";

        var res = wx.sendSocketMessage({
          data: login_data
        });
        console.log(login_data);
        console.log(res);
      });
    }

    wx.onSocketMessage(function(res) {
      let result = JSON.parse(res.data)
      console.log("d----------------------+" )
      console.log( result);
      console.log(JSON.parse(res.data).type)
      
      if(JSON.parse(res.data).type == 'login' || JSON.parse(res.data).type == 'say'){
        let pushM = that.data.pushMessage
        pushM.push(JSON.parse(res.data))
        that.setData({
          pushMessage: pushM
        }, () => {
          //滚动条至最底部 
          that.setData({
            toView:`item${that.data.pushMessage.length - 1}` 
          }, () => {
            console.log(that.data.toView)
          })
        })
      } 
      
      if (JSON.parse(res.data).type == 'login') {
   
        if (result.client_list){
          
          
          for (var i in result.client_list){
            console.log(i)
            that.data.client_list.push(i)
            that.setData({
              client_list_Length:that.data.client_list
            },()=>{
              // console.log(that.data.client_list_Length)
              that.setData({
                loginNum: that.data.client_list_Length.length
              })
            })
          }
        }else{
          let aa = that.data.loginNum+1
          // console.log('--------------------------/////////////////////x')
          // console.log(aa)
          that.setData({
            loginNum: aa
          })
        }
        
        
      }
      if (JSON.parse(res.data).type == 'logout') {
        
        let numser = that.data.loginNum - 1
        console.log(numser)
        that.setData({
          loginNum: numser
        })
      }
     
    });

    this.setData({
      mode: options.mode,
      orientation: options.orientation,
      enableCamera: options.enableCamera === "false" ? false : true,
      pushUrl: decodeURIComponent(options.pushUrl)
    });
  },
/**
 * 推送直播商品
 */
   pushOnlivegoods:function(event){
     var that = this;
     console.log('id======'+event.currentTarget.dataset.id); 
     var id = event.currentTarget.dataset.id
      var senddata =
        `{"type":"pushgoods","to_client_id":"all","to_client_name":"","content":${id}}`;

    var res = wx.sendSocketMessage({
      data: senddata
    });
      console.log(senddata);
       console.log(res);
    wx.request({
      url: `${app.globalData.dev}?op=SetMasetGoods&uniacid=${that.data.live['uniacid']}&goodsid=${id}`,
      success:function(res){
        console.log(res)
        if(res.data.status=='200'){
          that.setData({
            nowProduct:true
          },()=>{
           
            wx.request({
              url: `${app.globalData.natappvipindex}?i=${that.data.live['uniacid']}&c=entry&m=lexiangpingou&do=goods&ac=list&op=shopajax&is_hunda=1&page=1&pagesize=4&noliveinfo=1&nocategory=1`,
              data: '',
              header: {},
              method: 'GET',
              dataType: 'json',
              responseType: 'text',
              success: function (res) {
                // let list = JSON.parse()
                that.setData({
                  productList: res.data.list
                })
                console.log(res)
              },
              fail: function (res) { },
              complete: function (res) { },
            })

          })
        }
      },
      fail:function(res){
        console.log(res)
      }
    })
   },
   

  
  //  https://cch.natappvip.cc/applet/live.php ? op = SetMasetGoods & uniacid=2908 & goodsid=15 
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    console.log(" onReady");
    this.createContext();

    wx.setKeepScreenOn({
      keepScreenOn: true
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    console.log(" onShow");
    // 保持屏幕常亮
    // this.onLoad()
    // Object.assign(this, this.$options.data());
    wx.setKeepScreenOn({
      keepScreenOn: true
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    console.log(" onHide");
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    console.log(" onUnload");
    this.stop();
    // this.onLoad()\
    // console.log(wx.connectSocket)
    wx.closeSocket()
    wx.setKeepScreenOn({
      keepScreenOn: false
    });
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    console.log(" onShareAppMessage");
    return {
      // title: 'RTMP推流',
      // path: '/pages/push/push',
      path: "pages/home-login/main",
      imageUrl:
        "https://res.lexiangpingou.cn/images/applet/hdassistant_bg.png"
    };
  },
  onBack: function() {
   wx.closeSocket()
    wx.navigateBack({
      delta: 1
    });
  }
});
